import requests
from requests.auth import HTTPBasicAuth
import time
from pprint import pprint
import asyncio
import httpx

# 获取到时间范围，进行查询
def format_time_us(before_timestamp):
    """时间戳的长度不论是多少，我只取us级别的长度"""
    return int(str(before_timestamp)[:16])


def get_time_range(current_timestamp_ns = None,days = None):
    if not current_timestamp_ns:
        current_timestamp_ns = time.time_ns()
    if not days:
        days = -7
    befor_timestamp =  current_timestamp_ns + 1000 * 1000 * 1000 * 1 * 60 * 60 * 24 *(days)
    return (format_time_us(befor_timestamp),format_time_us(current_timestamp_ns))


# openobserve查询的工具类
class OpenObserveTools(object):
    def __init__(self,cookies={}):
        self.domain_name = "http://jd1.wwwfff.top:5080"
        self.cookies = {}
        self.headers = {
            "Content-Type": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36",
        }
        self.username = "fanghongjian@geetest.com"
        self.password = "admin123"
        

    def do_query(self, sql=None, start_time=None, end_time=None,page=0,page_size=10):
        if not sql:
            raise Exception("sql is None")
        current_time_us = time.time_ns()
        if not end_time:
            end_time = int(current_time_us / 1000)

        if not start_time:
            start_time = current_time_us - 1000 * 1000 * 1000 * 1 * 60 * 60 * 24 * 7
            start_time = int(start_time / 1000)
        json_data = {
            "query": {
                "sql": sql,
                "start_time": start_time,
                "end_time": end_time,
                "from": page,
                "size": page_size,
                "track_total_hits": True,
                "sql_mode": "context",
            }
        }
        response = requests.post(
            url=self.domain_name + "/api/default/_search",
            cookies=self.cookies,
            headers=self.headers,
            json=json_data,
            verify=False,
            auth=HTTPBasicAuth(username=self.username, password=self.password),
        )
        return response.json()
    
    async def do_query_async(self, sql=None, start_time=None, end_time=None,page=0,page_size=10):
        """
        异步的处理查询请求
        """
        if not sql:
            raise Exception("sql is None")
        start_time ,end_time  = get_time_range()
        json_data = {
            "query": {
                "sql": sql,
                "start_time": start_time,
                "end_time": end_time,
                "from": page,
                "size": page_size,
                "track_total_hits": True,
                "sql_mode": "context",
            }
        }
        async with httpx.AsyncClient() as client:  # 创建一个异步client
            response = await client.post(
            url=self.domain_name + "/api/default/_search",
            cookies=self.cookies,
            headers=self.headers,
            json=json_data,   
            auth=HTTPBasicAuth(username=self.username, password=self.password),
        )
            return response.json()
    

if __name__ == "__main__":
    # 异步的测试方法
    ttt = OpenObserveTools()
    res = asyncio.run(ttt.do_query_async(sql="""SELECT * FROM brde ORDER BY _timestamp DESC"""))
    pprint(res)
